package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.obrempon.credit.market.R
import com.obrempon.credit.market.base.app.ObremponActivityStackManager
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponLoginActBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpAct
import com.obrempon.credit.market.httptest.api.ObremponLoginApi
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.utils.ObremponDateUtil
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.TestAnalysisAddEvent
import com.obrempon.credit.market.utils.helper.ObremponAnalysisHelper
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import com.obrempon.credit.market.weight.font.RobotoMediumEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class ObremponLoginAct : HttpAct() {
    lateinit var binding: ObremponLoginActBinding

    override fun takeObremponRootView(): View {
        binding = ObremponLoginActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))
        rootViewBinding.rootContainer.setPadding(0, ObremponTitleBarUtil.getStatusBarHeight(), 0, 0)
        setObremponTitleBarVisibility(View.GONE)
        //关闭所有页面
        ObremponActivityStackManager.finishAllActivity(ObremponLoginAct::class.java)
        checkLoginBtnState()
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Login Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER, "Login Page")
        }
        binding.textMobile.setOnClickListener {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_LOGIN_SELF_MOBILE)
            requestObremponPhoneNumber()
        }
        binding.editMobile.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }

            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(ObremponEventPointType.FORM.OBREMPON_FORM_LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (takeObremponLoginMobile().isNotEmpty()) {
                    binding.editMobile.setTextColor(getColor(R.color.black))
                }
                checkLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.loginCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOGIN_PRIVACY_AGREE)
                }

                false -> {
                    addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener {
            binding.editMobile.clearFocus()
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOGIN_NEXT, takeObremponLoginMobile())
            onHideSoftInput(binding.editMobile)

            //登录之前，需要验证手机号是否在 app配置 accList 里存在
            val accItem = checkUserLoginConfigAccount()
            //accList 存在该手机号，直接进入登录成功流程
            if (accItem != null){
                ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_IS_CONFIG_ACCOUNT,true)
                onUserLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
                return@setOnClickListener
            }
            doLoginAction()
        }

        //隐私协议
        binding.textLoginPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.obrempon_privacy_policy_title)
            val linkUrl = ObremponConfigs.OBREMPON_PRIVACY_POLICY_ZMB_LINK
            ObremponWebviewAct.start(this, showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun takeObremponData() {
        val showZoneCode = "+${ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_TIMEZONE_CODE)}"
        val zoneCodeSpannable = SpannableString(showZoneCode)
        //添加下划线
        zoneCodeSpannable.setSpan(UnderlineSpan(), 0, showZoneCode.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginZoneCode.text = zoneCodeSpannable

        val showPrivacyPolicy = String.format(getString(R.string.obrempon_login_privacy_policy), getString(R.string.obrempon_privacy_policy_title))
        val privacyPolicySpannable = SpannableString(showPrivacyPolicy)
        val startIndex = showPrivacyPolicy.indexOf(getString(R.string.obrempon_privacy_policy_title))
        privacyPolicySpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ff0569ff)), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        privacyPolicySpannable.setSpan(UnderlineSpan(), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginPrivacyPolicy.text = privacyPolicySpannable

        binding.editMobile.visibility = View.GONE
        binding.textMobile.visibility = View.VISIBLE
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        binding.loginErrorLayout.visibility = View.INVISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.color_ff0569ff))
            .setStrokeSize(resources.getDimension(com.obrempon.module.R.dimen.dp_1).toInt())
            .intoBackground()
        if (binding.loginCheckBox.isChecked && takeObremponLoginMobile().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    fun takeObremponLoginMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    fun showObremponUserLoginFailure(data: JSONObject) {
        binding.loginErrorLayout.visibility = View.VISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.color_fffff6f6))
            .setStrokeColor(getColor(R.color.color_fff55555))
            .setStrokeSize(resources.getDimension(com.obrempon.module.R.dimen.dp_1).toInt())
            .intoBackground()
    }

    /**
     * 获取本机手机号码
     */
    private fun requestObremponPhoneNumber(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    ObremponLogger.e("Launching the PendingIntent failed")
                    showObremponInputMobile()
                }
            }
            .addOnFailureListener {
                ObremponLogger.e("Phone Number Hint failed : OnFailureListener")
                showObremponInputMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            ObremponLogger.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEventPointRequestAction(ObremponEventPointType.FORM.OBREMPON_FORM_USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(takeObremponLoginMobile().length)
        } catch(e: Exception) {
            ObremponLogger.e("Phone Number Hint failed：${e.message}")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            showObremponInputMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showObremponInputMobile(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.GONE

        launch(Dispatchers.Main){
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(takeObremponLoginMobile().length) // 将光标设置到文本末尾
        }
    }

    private fun showObremponMainHomePage() {
        onIntent(ObremponMainAct::class.java)
        finish()
    }

    /**
     * 登录成功
     */
    private fun onUserLoginSuccess(uid: String, token: String){
        hideObremponLoading()
        //保存手机号码，个人中心使用
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_MOBILE, takeObremponLoginMobile())
        //保存用户登录时间
        val loginTime = ObremponDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_LOGIN,true)
        //保存用户id
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_USERID,uid)
        //保存用户Token
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        ObremponAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        showObremponMainHomePage()
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUserLoginConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList 里存在
        val customize = ObremponConfigsHelper.takeObremponConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (takeObremponLoginMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录
     */
    private fun doLoginAction(){
        showObremponLoading()
        doHttpPostAction(ObremponLoginApi().subObremponLoginMobile(takeObremponLoginMobile()),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_IS_ADSOURCE,true)
                    }

                    //登录类型 == 注册，需要打点
                    if (type == "REGISTER"){
                        TestAnalysisAddEvent.addRegisterEvent()
                    }
                    onUserLoginSuccess(userId,userToken)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showObremponToast(error.optString("errorMsg"))
                showObremponUserLoginFailure(error)
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOGIN_END)
    }
}